--- 模块功能：MQTT客户端数据接收处理
-- @author openLuat
-- @module mqtt.mqttInMsg
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28
module(..., package.seeall)

require "config"
require "nvm"
require "earthquakeWarning"

-- 参数配置文件初始化
nvm.init("config.lua", true)
-- 变量初始化
local slen, errInfo, sysTime = string.len, "", ""
local earthquakeOpenOrnot = nvm.get("EarthquakeOpenOrnot")
-- 主题是否包含判断
local function isContainTopic(topic)
    local containTopic = false
    local topicList = {}
    local centerNameList = string.split(nvm.get("CenterName"), ",")
    for i = 1, #centerNameList, 1 do
        topicList[i] = "quake/" .. centerNameList[i]
        if topicList[i] == topic then containTopic = true end
    end
    return containTopic
end

--- MQTT客户端数据接收处理
-- @param mqttClient，MQTT客户端对象
-- @return 处理成功返回true，处理出错返回false
-- @usage mqttInMsg.proc(mqttClient)
function proc(mqttClient)
    local result, data, receiveMsg, base64DecodeMsg, aesDecryptMsg
    while true do
        sysTime = string.format("%04d-%02d-%02d %02d:%02d:%02d",
                                os.date("*t").year, os.date("*t").month,
                                os.date("*t").day, os.date("*t").hour,
                                os.date("*t").min, os.date("*t").sec)
        result, data = mqttClient:receive(60000, "APP_SOCKET_SEND_DATA")
        errInfo = ""
        -- 接收到数据
        log.info("mqtt61613 Result:", result)
        if result then
            aesDecryptMsg = data.payload
            base64DecodeMsg = crypto.base64_decode(aesDecryptMsg,
                                                   slen(aesDecryptMsg))
            aesDecryptMsg = crypto.aes_decrypt("ECB", "PKCS5", base64DecodeMsg,
                                               "keson-123abcdefg")
            local tjsondata, resultMqtt, errinfo = json.decode(aesDecryptMsg)
            local msgCode, unitId, todo, exercise
            log.info("mqtt payload", aesDecryptMsg)
            log.info("data.topic", data.topic)
            if isContainTopic(data.topic) then
                if resultMqtt and type(tjsondata) == "table" then
                    exercise, msgCode = tjsondata["exercise"], tjsondata["16"]
                    if exercise then -- 预警演练（云）
                        unitId = tonumber(tjsondata["13"])
                        if unitId == 125 then
                            if earthquakeOpenOrnot then
                                earthquakeWarningDril.EarthquakeWarningDrillSystem(
                                    tjsondata)
                            end

                        end
                    elseif msgCode == "0199" then -- 单位预警取消（包含演习及模拟）
                        unitId = tonumber(tjsondata["17"])
                        if unitId == 125 then
                            if earthquakeOpenOrnot then
                                earthquakeWarningDril.EarthquakeWarningDrillSystem(
                                    tjsondata)
                            end

                        else
                            errInfo = errInfo .. "[" .. sysTime .. "]" ..
                                          "[错误信息:]所属部门ID不相符！\n"
                        end
                    end
                    msgCode = tjsondata["2"]
                    log.info("msgCode", msgCode)
                    if msgCode == "0199" then -- 单位预警取消（包含演习及模拟）
                        if earthquakeOpenOrnot then
                            earthquakeWarning.EarthquakeWarning(aesDecryptMsg,
                                                                tjsondata)
                        end

                    elseif msgCode == "0101" or msgCode == "0102" then
                        if earthquakeOpenOrnot then
                            earthquakeWarning.EarthquakeWarning(aesDecryptMsg,
                                                                tjsondata)
                        end

                    end
                end
            else
                errInfo = errInfo .. "[" .. sysTime .. "]" ..
                              "[订阅主题满足要求:]" ..
                              "接收的主题:" .. data.topic .. "\n"
                -- logGenerator.generateLogTask(errInfo, "log")
            end
        else
            break
        end
    end
    log.info("MQTT TASK RESULT", result, "MQTT TASK DATA", data)
    return result or data == "timeout" or data == "APP_SOCKET_SEND_DATA"
end
